package com.alibaba.citrus.cr.platform.enhance.repository.impl;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.alibaba.acm.shaded.com.alibaba.metrics.StringUtils;
import com.alibaba.citrus.cr.platform.enhance.repository.CustomerAddressRelationRepository;
import com.alibaba.citrus.cr.platform.enhance.repository.CustomerRepository;
import com.alibaba.citrus.cr.platform.enhance.repository.CustomerSaleScopeRepository;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;

import com.epoch.app.bcorder.model.dto.*;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.crplatformenhance.api.customersalescopequery.dto.BatchQueryCustomerSaleScopeRequest;
import com.epoch.app.crplatformenhance.domain.customer.dto.CustomerLoadListRequest;
import com.epoch.app.crplatformenhance.domain.customer.model.Customer;
import com.epoch.app.crplatformenhance.domain.customer.service.CustomerService;
import com.epoch.app.crplatformenhance.domain.customersalescope.dto.*;
import com.epoch.app.crplatformenhance.domain.customersalescope.model.CustomerSaleScope;
import com.epoch.app.crplatformenhance.domain.customersalescope.service.CustomerSaleScopeService;
import com.epoch.app.crplatformenhance.domain.scitemgroup.dto.LoadScItemGroupListRequest;
import com.epoch.app.crplatformenhance.domain.scitemgroup.model.ScItemGroup;
import com.epoch.app.crplatformenhance.domain.scitemgroup.service.ScItemGroupService;
import com.epoch.app.crplatformenhance.dto.request.CustomerBatchRequest;
import com.epoch.app.crplatformenhance.dto.request.QuerySaleScopeRequest;
import com.epoch.app.crplatformenhance.model.dto.CustomerAddressRelationLoadListRequest;
import com.epoch.app.crplatformenhance.model.dto.CustomerAddressRelationSDO;
import com.epoch.app.crplatformenhance.model.enums.CustomerRelationBizTypeEnum;
import com.epoch.app.crplatformenhance.sdo.CustomerSDO;
import com.epoch.app.crplatformenhance.sdo.CustomerSaleScopeSDO;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

@Component
public class CustomerSaleScopeRepositoryImpl implements CustomerSaleScopeRepository {
    private static final Log log = Log.getLogger(CustomerSaleScopeRepositoryImpl.class);

    @Resource
    private CustomerSaleScopeService customerSaleScopeService;

    @Resource
    private BaseDataService baseDataService;

    @Resource
    private ScItemGroupService scItemGroupService;

    @Resource
    private CustomerRepository customerRepository;

    @Resource
    private CustomerAddressRelationRepository customerAddressRelationRepository;

    @Resource
    private CustomerService customerService;

    @Override
    public Boolean edit(CustomerSaleScopeSDO saleScopeSDO) {
        log.info("CustomerSaleScopeRepositoryImpl.edit接口入参" + JSONObject.toJSONString(saleScopeSDO));
        CustomerSaleScope updateRequest = new CustomerSaleScope();
        BeanUtils.copyProperties(saleScopeSDO, updateRequest);
        Set<String> platform = new HashSet<>();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(saleScopeSDO.getCommercePlatform())) {
            List<PlatformSDO> queryPlatforms1 = baseDataService.baselineBatchQueryPlatforms2(BaselineBatchQueryPlatforms2Request.builder().platformIds(Lists.newArrayList(saleScopeSDO.getCommercePlatform())).build()).getResult();
            if (CollectionUtils.isNotEmpty(queryPlatforms1)) {
                for (PlatformSDO platformSDO : queryPlatforms1) {
                    platform.add(platformSDO.getPlatformName());
                }
            }
            //判断传入的是否是页面回显的中文
            if (platform.contains(saleScopeSDO.getCommercePlatform())) {
                List<PlatformSDO> queryPlatforms2 = baseDataService.baselineBatchQueryPlatforms2(BaselineBatchQueryPlatforms2Request.builder().platformNames(Lists.newArrayList(saleScopeSDO.getCommercePlatform())).build()).getResult();
                String platformCode1 = queryPlatforms2.get(0).getPlatformCode();
                updateRequest.setCommercePlatform(platformCode1);
            } else {
                //如果不包含说明传入的重选的id  那么就根据id去查询就可以
                List<PlatformSDO> queryPlatforms3 = baseDataService.baselineBatchQueryPlatforms2(BaselineBatchQueryPlatforms2Request.builder().platformIds(Lists.newArrayList(saleScopeSDO.getCommercePlatform())).build()).getResult();
                String platformCode2 = queryPlatforms3.get(0).getPlatformCode();
                updateRequest.setCommercePlatform(platformCode2);
            }
        } else {
            //如果在编辑的时候 把电商平台去除了 那么就滞空进行修改
            updateRequest.setCommercePlatform("");
        }
        //如果在分派或导入时  负责人为空 则置为空值 进行修改
        if (org.apache.commons.lang3.StringUtils.isBlank(saleScopeSDO.getPrincipal())) {
            updateRequest.setPrincipal("");
        }
        if (StringUtils.isNotBlank(saleScopeSDO.getCommercePlatformCode())) {
            updateRequest.setCommercePlatform(saleScopeSDO.getCommercePlatformCode());
        }
        updateRequest.setId(Long.parseLong(saleScopeSDO.getId()));
        updateRequest.setUpdater(saleScopeSDO.getUpdater());
        updateRequest.setGmtModified(new Date());
        Integer count = 0;
        try {
            log.info("CustomerSaleScopeRepositoryImpl.update入参" + JSONObject.toJSONString(updateRequest));
            UpdateCustomerSaleScopeResponse response = customerSaleScopeService.updateCustomerSaleScope(updateRequest);
            count = response.getCount();
            log.info("CustomerSaleScopeRepositoryImpl.update返回值:" + count);
            if (count == 0) {
                return false;
            }
        } catch (Exception e) {
            throw new RuntimeException("数据更新失败");
        }
        log.info("CustomerSaleScopeRepositoryImpl.edit成功");
        return true;
    }

    @Override
    public List<CustomerSaleScopeSDO> queryList(CustomerSaleScopeSDO customerSaleScopeSDO) {
        CustomerSaleScopeLoadListRequest loadListRequest = new CustomerSaleScopeLoadListRequest();
        BeanUtils.copyProperties(customerSaleScopeSDO, loadListRequest);
        loadListRequest.setDir("gmt_create");
        Result<List<CustomerSaleScope>> saleScopeResult = customerSaleScopeService.loadCustomerSaleScopeList(loadListRequest);
        //  List<CustomerSaleScopeSDO> resultList = new ArrayList<>();
        List<CustomerSaleScopeSDO> resultList = saleScopeResult.getResult().stream().map(saleScope -> {
            CustomerSaleScopeSDO saleScopeSDO = new CustomerSaleScopeSDO();
            BeanUtils.copyProperties(saleScope, saleScopeSDO);
            saleScopeSDO.setId(saleScope.getId().toString());
            JSONObject jsonobject = JSONObject.parseObject(saleScope.getFeatures());
            String itemGroupName = (String) jsonobject.get("itemGroupName");
            saleScopeSDO.setItemGroupName(itemGroupName);
            return saleScopeSDO;
        }).collect(Collectors.toList());

//        for (CustomerSaleScope saleScope : saleScopeResult.getResult()) {
//            CustomerSaleScopeSDO saleScopeSDO = new CustomerSaleScopeSDO();
//            BeanUtils.copyProperties(saleScope, saleScopeSDO);
//            saleScopeSDO.setId(saleScope.getId().toString());
//            resultList.add(saleScopeSDO);
//        }
        return resultList;
    }

    @Override
    public PageResult<List<CustomerSaleScopeSDO>> pageQuery(QuerySaleScopeRequest request) {
        log.info("CustomerSaleScopeRepositoryImpl_pageQuery_request:" + JSONObject.toJSONString(request));
        LoadCustomerSaleScopeList2Request loadListRequest = new LoadCustomerSaleScopeList2Request();
        BeanUtils.copyProperties(request, loadListRequest);

        if (StringUtils.isNotBlank(request.getId())) {
            loadListRequest.setId(Long.valueOf(request.getId()));
        }
        if (CollectionUtils.isNotEmpty(request.getOrgSaleChannelCodeList())) {
            loadListRequest.setOrgSaleChannelCodeList(request.getOrgSaleChannelCodeList());
        }
        if (CollectionUtils.isNotEmpty(request.getOrgSaleDepartmentCodeList())) {
            loadListRequest.setOrgSaleDepartmentCodeList(request.getOrgSaleDepartmentCodeList());
        }

        //查询条件 客户编码，客户名称
        if (StringUtils.isNotBlank(request.getCustomerCode1())) {
            loadListRequest.setCustomerCode(request.getCustomerCode1());
        }
        if (StringUtils.isNotBlank(request.getCustomerName())) {
            Result<List<Customer>> listResult = customerService.loadCustomerList(CustomerLoadListRequest.newCustomerLoadListRequestBuilder().name(request.getCustomerName()).build());
            if (CollectionUtils.isNotEmpty(listResult.getResult())) {
                List<String> customerCodes = listResult.getResult().stream().map(Customer::getCode).collect(Collectors.toList());
                loadListRequest.setCustomerCodeList(customerCodes);
            }
        }

        //查询条件 电商平台
        if (CollectionUtils.isNotEmpty(request.getCommercePlatformList())) {
            loadListRequest.setCommercePlatformList(request.getCommercePlatformList());
        }
        if (StringUtils.isNotBlank(request.getCommercePlatform())) {//电商平台id转code
            List<PlatformSDO> result = baseDataService.baselineBatchQueryPlatforms2(BaselineBatchQueryPlatforms2Request.builder().platformIds(Lists.newArrayList(request.getCommercePlatform())).build()).getResult();
            if (CollectionUtils.isNotEmpty(result)) {
                for (PlatformSDO platformSDO : result) {
                    loadListRequest.setCommercePlatform(platformSDO.getPlatformCode());
                }
            }
        }

        //查询条件 客户方负责人
        List<Long> saleScopIds = null;
        if (StringUtils.isNotBlank(request.getCustomerPrincipal())){
            List<CustomerAddressRelationSDO> result = customerAddressRelationRepository.queryRelationList(CustomerAddressRelationLoadListRequest.newCustomerAddressRelationLoadListRequestBuilder()
                    .relationId(request.getCustomerPrincipal())
                    .bizType(CustomerRelationBizTypeEnum.SALESCOPE_CUSTOMER_PRINCIPAL_RELATION.getValue())
                    .build());
            if (CollectionUtils.isEmpty(result)){
                return PageResult.empty();
            }

            saleScopIds = result.stream().map(x->Long.valueOf(x.getAddressId())).collect(Collectors.toList());
            loadListRequest.setIdList(saleScopIds);
        }

        loadListRequest.setDir("gmt_create");

        Result<List<CustomerSaleScope>> saleScopeResult = customerSaleScopeService.loadCustomerSaleScopeList2(loadListRequest);
        log.info("CustomerSaleScopeRepositoryImpl_pageQuery_loadCustomerSaleScopeList2_request={},result={}",JSONObject.toJSONString(loadListRequest),JSONObject.toJSONString(saleScopeResult));

        //查询结果转换下组织名称
        Set<String> orgSaleOrgCodes = saleScopeResult.getResult().stream().map(CustomerSaleScope::getOrgSaleOrganizationCode).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        Set<String> orgSaleChannelCodes = saleScopeResult.getResult().stream().map(CustomerSaleScope::getOrgSaleChannelCode).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        Set<String> orgSaleDepartmentCodes = saleScopeResult.getResult().stream().map(CustomerSaleScope::getOrgSaleDepartmentCode).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        Set<String> codes = Sets.newHashSet();
        codes.addAll(orgSaleOrgCodes);
        codes.addAll(orgSaleChannelCodes);
        codes.addAll(orgSaleDepartmentCodes);
        BaselineGetOrganizationByIds2Request byIds2Request = new BaselineGetOrganizationByIds2Request();
        byIds2Request.setIds(Lists.newArrayList(codes));
        byIds2Request.setStatus(1);
        BaselineGetOrganizationByIds2Response byIds2Response = baseDataService.baselineGetOrganizationByIds2(byIds2Request);
        //log.error("CustomerSaleScopeRepositoryImpl_baseDataService_baselineGetOrganizationByIds_request=",JSONObject.toJSONString(byIds2Request),JSONObject.toJSONString(byIds2Response));
        if (byIds2Response == null || CollectionUtils.isEmpty(byIds2Response.getResult())) {
            return new PageResult<List<CustomerSaleScopeSDO>>();
        }
        Map<String, OrganizationSDO> organizationSDOMap = byIds2Response.getResult().stream().collect(Collectors.toMap(OrganizationSDO::getId, o -> o));

        //查询结果转换下负责人名称
        Set<String> persons = saleScopeResult.getResult().stream().map(CustomerSaleScope::getPrincipal).collect(Collectors.toSet());
        Set<String> creators = saleScopeResult.getResult().stream().map(it -> it.getCreator().replace("CZ_", "")).filter(org.apache.commons.lang3.StringUtils::isNotBlank).collect(Collectors.toSet());
        Set<String> updaters = saleScopeResult.getResult().stream().map(it -> it.getUpdater().replace("CZ_", "")).filter(org.apache.commons.lang3.StringUtils::isNotBlank).collect(Collectors.toSet());
        persons.addAll(creators);
        persons.addAll(updaters);
        BaselineGetEmployeeByIdsAllRequest byIdsRequest = BaselineGetEmployeeByIdsAllRequest.builder().ids(Lists.newArrayList(persons)).build();
        Result<List<EmployeeSDO>> listResult = baseDataService.baselineGetEmployeeByIdsAll(byIdsRequest);
        Map<String, EmployeeSDO> employeeSDOMap = Maps.newHashMap();
        if (Objects.nonNull(listResult) && CollectionUtils.isNotEmpty(listResult.getResult())) {
            List<EmployeeSDO> employeeSDOS = listResult.getResult();
            employeeSDOMap = employeeSDOS.stream().collect(Collectors.toMap(EmployeeSDO::getId, o -> o));
        }
        Map<String, EmployeeSDO> finalEmployeeSDOMap = employeeSDOMap;

        //查询结果转换下客户名称
        Set<String> customerCodes = saleScopeResult.getResult().stream().map(CustomerSaleScope::getCustomerCode).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        CustomerBatchRequest customerBatchRequest = CustomerBatchRequest.builder().codes(Lists.newArrayList(customerCodes)).build();
        List<CustomerSDO> customerSDOS = customerRepository.batchQuery(customerBatchRequest);
        //log.error("CustomerSaleScopeRepositoryImpl_customerRepository_batchQuery_request={},result={}",JSONObject.toJSONString(customerBatchRequest),JSONObject.toJSONString(customerSDOS));
        Map<String, CustomerSDO> customerSDOMap = Maps.newHashMap();
        if (CollectionUtils.isNotEmpty(customerSDOS)) {
            customerSDOMap = customerSDOS.stream().collect(Collectors.toMap(CustomerSDO::getCode, o -> o));
        }
        Map<String, CustomerSDO> finalCustomerSDOMap = customerSDOMap;

        //查询结果转换下业务渠道名称
        Set<String> channelCodes = saleScopeResult.getResult().stream().map(CustomerSaleScope::getChannelCode).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        BaselineBatchQueryChannels2Request queryChannels2Request = BaselineBatchQueryChannels2Request.builder().channelCodes(Lists.newArrayList(channelCodes)).build();
        Result<List<ChannelSDO>> channelSDOS = baseDataService.baselineBatchQueryChannels2(queryChannels2Request);
        Map<String, ChannelSDO> channelSDOMap = Maps.newHashMap();
        if (CollectionUtils.isNotEmpty(channelSDOS.getResult())) {
            channelSDOMap = channelSDOS.getResult().stream().collect(Collectors.toMap(ChannelSDO::getChannelCode, o -> o));
        }
        Map<String, ChannelSDO> finalChannelSDOMap = channelSDOMap;

        //查询结果转换下电商平台名称
        Map<String, PlatformSDO> platformSDOMap = Maps.newHashMap();
        Set<String> commercePlatforms = saleScopeResult.getResult().stream().map(CustomerSaleScope::getCommercePlatform).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        if(CollectionUtils.isNotEmpty(commercePlatforms)){
            BaselineBatchQueryPlatforms2Request queryPlatforms2Request = BaselineBatchQueryPlatforms2Request.builder().platformCodes(Lists.newArrayList(commercePlatforms)).build();
            Result<List<PlatformSDO>> platformSDOS = baseDataService.baselineBatchQueryPlatforms2(queryPlatforms2Request);
            if (CollectionUtils.isNotEmpty(platformSDOS.getResult())) {
                platformSDOMap = platformSDOS.getResult().stream().collect(Collectors.toMap(PlatformSDO::getPlatformCode, o -> o));
            }
        }
        Map<String, PlatformSDO> finalPlatformSDOMap = platformSDOMap;

        //货品组名称,当前SAP货品组只有1个货品租
        Set<String> itemGroups = saleScopeResult.getResult().stream().map(CustomerSaleScope::getItemGroup).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        List<String> itemGroupList = Lists.newArrayList(itemGroups);
        if(CollectionUtils.isNotEmpty(itemGroupList) && itemGroupList.size()>1){
            log.info("CustomerSaleScopeRepositoryImpl_pageQuery_pageItemGroup_size={}",itemGroupList.size());
        }
        LoadScItemGroupListRequest itemGroupListRequest = LoadScItemGroupListRequest.builder().code(itemGroupList.get(0)).build();
        Result<List<ScItemGroup>> itemGroupResult = scItemGroupService.loadScItemGroupList(itemGroupListRequest);
        ScItemGroup scItemGroup = itemGroupResult.getResult().stream().findFirst().get();

        //客户方负责人
        Map<String, List<CustomerAddressRelationSDO>> customerAddressRelationMap = Maps.newHashMap();
        Set<String> ids = saleScopeResult.getResult().stream().map(x-> String.valueOf(x.getId())).collect(Collectors.toSet());
        CustomerAddressRelationLoadListRequest relationLoadListRequest = new CustomerAddressRelationLoadListRequest();
        relationLoadListRequest.setAddressIds(Lists.newArrayList(ids));
        relationLoadListRequest.setBizType(CustomerRelationBizTypeEnum.SALESCOPE_CUSTOMER_PRINCIPAL_RELATION.getValue());
        List<CustomerAddressRelationSDO> relationResult = customerAddressRelationRepository.queryRelationList(relationLoadListRequest);
        if (CollectionUtils.isNotEmpty(relationResult)) {
            customerAddressRelationMap = relationResult.stream().collect(Collectors.groupingBy(CustomerAddressRelationSDO::getAddressId));
        }
        Map<String, List<CustomerAddressRelationSDO>> finalCustomerAddressRelationMap = customerAddressRelationMap;

        List<CustomerSaleScopeSDO> resultList = saleScopeResult.getResult().stream().map(saleScope -> {
            CustomerSaleScopeSDO saleScopeSDO = new CustomerSaleScopeSDO();
            BeanUtils.copyProperties(saleScope, saleScopeSDO);
            saleScopeSDO.setId(saleScope.getId().toString());
            if (StringUtil.isNotEmpty(saleScope.getFeatures())) {
                JSONObject jsonobject = JSONObject.parseObject(saleScope.getFeatures());
                String channelName = jsonobject.getString("channelName");
                String itemGroupName = jsonobject.getString("itemGroupName");
                String salesAreaName = jsonobject.getString("salesAreaName");
                String transportAreaName = jsonobject.getString("transportAreaName");
                String customerName = jsonobject.getString("customerName");
                String transportArea = jsonobject.getString("transportArea");
                String outOrgSalesDepartmentCode = jsonobject.getString("outOrgSalesDepartmentCode");
                String outOrgSalesDepartmentName = jsonobject.getString("outOrgSalesDepartmentName");
                String outOrgSalesChannelCode = jsonobject.getString("outOrgSalesChannelCode");
                String outOrgSalesChannelName = jsonobject.getString("outOrgSalesChannelName");
                String storeHouse = jsonobject.getString("storeHouse");
                saleScopeSDO.setItemGroupName(itemGroupName);
                saleScopeSDO.setChannelName(channelName);
                saleScopeSDO.setSalesAreaName(salesAreaName);
                saleScopeSDO.setTransportAreaName(transportAreaName);
                saleScopeSDO.setCustomerName(customerName);
                saleScopeSDO.setTransportArea(transportArea);
                saleScopeSDO.setOutOrgSalesDepartmentCode(outOrgSalesDepartmentCode);
                saleScopeSDO.setOutOrgSalesDepartmentName(outOrgSalesDepartmentName);
                saleScopeSDO.setOutOrgSalesChannelCode(outOrgSalesChannelCode);
                saleScopeSDO.setOutOrgSalesChannelName(outOrgSalesChannelName);
                saleScopeSDO.setStoreHouse(storeHouse);
            }

            //组织名称
            OrganizationSDO orgSaleOrganization = organizationSDOMap.get(saleScope.getOrgSaleOrganizationCode());
            if(Objects.nonNull(orgSaleOrganization)){
                saleScopeSDO.setOrgSalesOrganizationName(orgSaleOrganization.getName());
                saleScopeSDO.setOrgSalesOrganizationCode2(orgSaleOrganization.getCode());
            }
            OrganizationSDO orgSaleChannel = organizationSDOMap.get(saleScope.getOrgSaleChannelCode());
            if(Objects.nonNull(orgSaleChannel)) {
                saleScopeSDO.setOrgSalesChannelName(orgSaleChannel.getName());
                saleScopeSDO.setOrgSalesChannelCode2(orgSaleChannel.getCode());
            }
            OrganizationSDO orgSaleDepartment = organizationSDOMap.get(saleScope.getOrgSaleDepartmentCode());
            if(Objects.nonNull(orgSaleDepartment)) {
                saleScopeSDO.setOrgSalesDepartmentName(orgSaleDepartment.getName());
                saleScopeSDO.setOrgSalesDepartmentCode2(orgSaleDepartment.getCode());
            }

            EmployeeSDO creator = finalEmployeeSDOMap.get(saleScope.getCreator().replace("CZ_", ""));
            if (Objects.nonNull(creator)) {
                saleScopeSDO.setCreatorName(creator.getName());
            }
            EmployeeSDO updater = finalEmployeeSDOMap.get(saleScope.getUpdater().replace("CZ_", ""));
            if (Objects.nonNull(updater)) {
                saleScopeSDO.setUpdaterName(updater.getName());
            }
            //负责人
            EmployeeSDO employeeSDO = finalEmployeeSDOMap.get(saleScope.getPrincipal());
            if (Objects.nonNull(employeeSDO)) {
                saleScopeSDO.setPrincipalName(employeeSDO.getName());
                saleScopeSDO.setNick(employeeSDO.getNick());
            }
            //客户名称
            CustomerSDO customerSDO = finalCustomerSDOMap.get(saleScope.getCustomerCode());
            if (Objects.nonNull(customerSDO)) {
                saleScopeSDO.setCustomerName(customerSDO.getName());
            }
            //渠道名称
            ChannelSDO channelSDO = finalChannelSDOMap.get(saleScope.getChannelCode());
            if (Objects.nonNull(channelSDO)) {
                saleScopeSDO.setChannelName(channelSDO.getChannelName());
            }
            //平台名称
            PlatformSDO platformSDO = finalPlatformSDOMap.get(saleScope.getCommercePlatform());
            if (Objects.nonNull(platformSDO)) {
                saleScopeSDO.setCommercePlatform(platformSDO.getPlatformName());
                saleScopeSDO.setCommercePlatformCode(platformSDO.getPlatformCode());
            }
            //货品组名称
            if(StringUtils.isNotBlank(saleScope.getItemGroup())){
                saleScopeSDO.setItemGroupName(scItemGroup.getName());
            }

            //客户方负责人
            saleScopeSDO.setCustomerPrincipalName("");
            List<CustomerAddressRelationSDO> relationList = finalCustomerAddressRelationMap.get(saleScopeSDO.getId());
            if(CollectionUtils.isNotEmpty(relationList)){
                String relationNameStr = relationList.stream().map(CustomerAddressRelationSDO::getRelationName).collect(Collectors.toList()).toString();
                List<String> relationIdList = relationList.stream().map(CustomerAddressRelationSDO::getRelationId).collect(Collectors.toList());
                saleScopeSDO.setCustomerPrincipalName(relationNameStr.substring(1,relationNameStr.length()-1));
                List<String> nickList = relationList.stream().map(x-> {
                    String featuresString = x.getFeatures();
                    if(StringUtils.isNotBlank(featuresString)){
                        return (String)JSONObject.parseObject(featuresString,Map.class).get("nick");
                    }
                    return null;
                }).collect(Collectors.toList());
                String nickStr = nickList.stream().filter(StringUtils::isNotBlank).collect(Collectors.toList()).toString();
                saleScopeSDO.setCustomerPrincipalNick(nickStr.substring(1,nickStr.length()-1));
                saleScopeSDO.setCustomerPrincipalList(relationIdList);
            }

            return saleScopeSDO;
        }).collect(Collectors.toList());

        return PageResult.of(resultList, saleScopeResult.getTotal());
    }

    @Override
    public CustomerSaleScopeSDO load(String id) {
        LoadCustomerSaleScopeRequest loadRequest = new LoadCustomerSaleScopeRequest();
        loadRequest.setId(id);
        CustomerSaleScope customerSaleScope = new CustomerSaleScope();
        try {
            customerSaleScope = customerSaleScopeService.loadCustomerSaleScope(loadRequest);
        } catch (Exception e) {
            return null;
        }
        CustomerSaleScopeSDO saleScopeSDO = new CustomerSaleScopeSDO();
        BeanUtils.copyProperties(customerSaleScope, saleScopeSDO);
        saleScopeSDO.setId(String.valueOf(customerSaleScope.getId()));
        return saleScopeSDO;
    }

    @Override
    public List<CustomerSaleScopeSDO> batchQueryCustomerSaleScopeByCustomerCodes(BatchQueryCustomerSaleScopeRequest batchQueryCustomerSaleScopeRequest) {
        List<String> customerCodes = batchQueryCustomerSaleScopeRequest.getCustomerCodes();
        if (Objects.isNull(customerCodes)) {
            return Lists.newArrayList();
        }
        BatchQueryByCustomerCodesRequest customerCodesRequest = BatchQueryByCustomerCodesRequest.builder().customerCodes(customerCodes).build();
        Result<List<CustomerSaleScope>> customerSaleScopeResult = customerSaleScopeService.batchQueryByCustomerCodes(customerCodesRequest);
        if (customerSaleScopeResult!=null && CollectionUtils.isEmpty(customerSaleScopeResult.getResult())) {
            return Lists.newArrayList();
        }
        List<CustomerSaleScopeSDO> objects = customerSaleScopeResult.getResult().stream().map(it -> {
            JSONObject jsonObject = JSONObject.parseObject(it.getFeatures());
            String storeHouse = jsonObject.getString("storeHouse");
            CustomerSaleScopeSDO customerSaleScopeSDO = new CustomerSaleScopeSDO();
            BeanUtils.copyProperties(it, customerSaleScopeSDO);
            customerSaleScopeSDO.setStoreHouse(storeHouse);
            return customerSaleScopeSDO;
        }).collect(Collectors.toList());
        return objects;
    }

    @Override
    public List<CustomerSaleScopeSDO> batchQueryCustomerSaleScopeByIds(BatchQueryByIdsRequest batchQueryByIdsRequest) {
        List<String> ids = batchQueryByIdsRequest.getIds();
        if (Objects.isNull(ids)) {
            return Lists.newArrayList();
        }

        Result<List<CustomerSaleScope>> customerSaleScopeResult = customerSaleScopeService.batchQueryByIds(batchQueryByIdsRequest);
        if (customerSaleScopeResult!=null && CollectionUtils.isEmpty(customerSaleScopeResult.getResult())) {
            return Lists.newArrayList();
        }

        //查询结果转换下客户名称
        Set<String> customerCodes = customerSaleScopeResult.getResult().stream().map(CustomerSaleScope::getCustomerCode).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        CustomerBatchRequest customerBatchRequest = CustomerBatchRequest.builder().codes(Lists.newArrayList(customerCodes)).build();
        List<CustomerSDO> customerSDOS = customerRepository.batchQuery(customerBatchRequest);
        Map<String, CustomerSDO> customerSDOMap = Maps.newHashMap();
        if (CollectionUtils.isNotEmpty(customerSDOS)) {
            customerSDOMap = customerSDOS.stream().collect(Collectors.toMap(CustomerSDO::getCode, o -> o));
        }
        Map<String, CustomerSDO> finalCustomerSDOMap = customerSDOMap;

        List<CustomerSaleScopeSDO> objects = customerSaleScopeResult.getResult().stream().map(it -> {
            CustomerSaleScopeSDO customerSaleScopeSDO = new CustomerSaleScopeSDO();
            BeanUtils.copyProperties(it, customerSaleScopeSDO);
            customerSaleScopeSDO.setId(it.getId().toString());
            //客户名称
            CustomerSDO customerSDO = finalCustomerSDOMap.get(customerSaleScopeSDO.getCustomerCode());
            if (Objects.nonNull(customerSDO)) {
                customerSaleScopeSDO.setCustomerName(customerSDO.getName());
            }
            return customerSaleScopeSDO;
        }).collect(Collectors.toList());
        return objects;
    }


}
